package net.xxcl.kygl.controller;

import net.xxcl.kygl.model.ProjectForUser;
import net.xxcl.kygl.pojo.Criteria;
import net.xxcl.kygl.pojo.Project;
import net.xxcl.kygl.pojo.ProjectType;
import net.xxcl.kygl.pojo.User;
import net.xxcl.kygl.service.ProjectService;
import net.xxcl.kygl.service.ProjectTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * User: 夏汛
 * Date: 12-9-28
 * Time: 下午5:41
 */
@Controller
@RequestMapping("/otherProject")
public class OtherProjectController {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectTypeService projectTypeService;
    /**
     * 获取用户参与的其它课题
     * @return
     */
    @RequestMapping(value = "/listProjectForUser",method= RequestMethod.POST)
    public @ResponseBody
    Map<String,Object> listProjectForUser(@RequestParam("start") Integer start,@RequestParam("limit") Integer limit,
                                          HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        User user = (User)request.getSession().getAttribute("user");
        Criteria criteria = new Criteria();
        criteria.put("outschool", 1);
        criteria.put("iscross",0);
        criteria.put("userid",user.getId());
        criteria.setOrderByClause("id desc");
        int total = projectService.countByUserId(criteria);
        List<ProjectForUser> list = projectService.selectByUserId(criteria);
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    /**
     * 上报纵向课题
     * @param project
     * @param request
     * @param response
     */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> save(@ModelAttribute("Project") Project project,
                     HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年");
        try{
            int projectTypeId = Integer.parseInt(request.getParameter("projectType"));
            //查出项目类型名称，供目录命名用
            project.setProjecttype(projectTypeId);
            ProjectType projectType = projectTypeService.selectByPrimaryKey(projectTypeId);
            project.setApprovaltime(sdf.parse(request.getParameter("otherstarttime")));
            if(project.getState()==0){
                project.setPlanendtime(sdf.parse(request.getParameter("otherendtime")));
            } else {
                project.setEndtime(sdf.parse(request.getParameter("otherendtime")));
            }
            String filePath = "upload" + File.separator
                    + sdf2.format(project.getApprovaltime()) + File.separator + "科研课题" + File.separator
                    + projectType.getName() + File.separator + UUID.randomUUID() + File.separator + project.getName()
                    + File.separator;
            project.setFilepath(filePath);
            projectService.addOtherProject(project,request.getParameter("ids"));
            responseMap.put("success",true);
            responseMap.put("info","上报成功，请及时上传课题材料");
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","上报失败，请重试");
        }
        return responseMap;
    }

    @RequestMapping(value = "/listforsh",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> listForZqjcsh(@RequestParam(value = "start") Integer start,
                                     @RequestParam(value = "limit") Integer limit){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        Criteria criteria = new Criteria();
        criteria.put("outschool",1);
        criteria.put("outschoolstate",1);
        criteria.put("iscross", 0);
        criteria.setOrderByClause("t_project.id desc");
        int total = projectService.countByExample(criteria);
        criteria.setMysqlOffset(start);
        criteria.setMysqlLength(limit);
        List<Project> list = projectService.selectByExample(criteria);
        for(Project project:list){
            List<Map> users = projectService.getUserByProjectId(project.getId());
            if(users.get(0).get("deptname")!=null){
                project.setDeptname((String) users.get(0).get("deptname"));
            }
            StringBuffer sb = new StringBuffer();
            for(Map user:users){
                if((Boolean)user.get("iscolleague")){
                    sb.append(","+user.get("username"));
                } else {
                    sb.append(",("+user.get("username")+")");
                }
            }
            project.setNames(sb.substring(1));
        }
        responseMap.put("total",total);
        responseMap.put("rows",list);
        return responseMap;
    }

    @RequestMapping(value = "/submitProjectOtherktsh",method= RequestMethod.POST)
    public @ResponseBody Map<String,Object> submitProjectZqjc(
            @RequestParam(value = "isagree") Boolean isagree,@RequestParam(value = "projectid") Integer projectid,
            HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> responseMap = new HashMap<String, Object>();
        try{
            Project project = projectService.selectByPrimaryKey(projectid);
            if(isagree){
                //检查通过
                if(project.getState()==0){
                    project.setState(3);
                } else if (project.getState()==6 || project.getState()==8){
                    project.setState(11);
                } else {
                    responseMap.put("info","课题状态异常");
                    return responseMap;
                }
            } else {
                //检查不通过
                if(project.getState()==0){
                    project.setState(2);
                } else if (project.getState()==6){
                    project.setState(7);
                } else if (project.getState()==8){
                    project.setState(10);
                } else {
                    responseMap.put("info","课题状态异常");
                    return responseMap;
                }
            }
            projectService.updateByPrimaryKeySelective(project);
            responseMap.put("success", "true");
            if(isagree){
                responseMap.put("info", "审核通过");
            } else {
                responseMap.put("info", "审核不通过");
            }
        } catch (Exception e){
            e.printStackTrace();
            responseMap.put("info","课题状态改变失败");
        }
        return responseMap;
    }
}
